import { ref, computed, onMounted, nextTick } from 'vue'
import { Modal, message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Key } from 'ant-design-vue/es/table/interface'
import type { DataNode } from 'ant-design-vue/es/tree'
import type { RolePermissionTreeNode } from '@/types/api/system/role'
import { useRoleStore } from '@/stores/system/role'
import { storeToRefs } from 'pinia'
import type { TablePaginationConfig } from 'ant-design-vue'

/**
 * 角色管理页面逻辑钩子
 * @returns 角色管理状态和方法
 */
export default function useRoleManagement() {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 使用状态管理 ------------
  const roleStore = useRoleStore()
  
  // 从store中提取响应式状态
  const { 
    loading, 
    submitLoading, 
    permissionLoading,
    roleList,
    formModalVisible: modalVisible, 
    permissionModalVisible,
    formData: form,
    pagination,
    queryParams,
    permissionTree: storePermissionTree,
    checkedKeys,
    currentRoleId
  } = storeToRefs(roleStore)
  
  // ------------ 组件引用 ------------
  const formRef = ref<FormInstance>()
  
  // ------------ 本地状态 ------------
  const selectedRowKeys = ref<Key[]>([])
  const treeData = ref<DataNode[]>([])
  const defaultExpandedKeys = ref<string[]>([])
  
  // ------------ 错误处理状态 ------------
  const loadError = ref(false)
  const errorMessage = ref('')
  
  // ------------ 计算属性 ------------
  const hasSelected = computed(() => selectedRowKeys.value.length > 0)
  
  // ------------ 表格交互方法 ------------
  /**
   * 表格选择行变化
   * @param keys 选中的键列表
   */
  const onSelectChange = (keys: Key[]) => {
    selectedRowKeys.value = keys
  }

  /**
   * 表格分页、排序、筛选变化处理
   * @param pagination 分页信息
   * @param filters 筛选条件
   * @param sorter 排序条件
   */
  const handleTableChange = (pagination: TablePaginationConfig) => {
    roleStore.handlePageChange(pagination.current || 1, pagination.pageSize || 10)
  }
  
  // ------------ 搜索区域方法 ------------
  /**
   * 搜索
   */
  const handleSearch = () => {
    roleStore.fetchRoleList(queryParams.value)
  }

  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    roleStore.resetQuery()
  }
  
  // ------------ 表单操作方法 ------------
  /**
   * 添加角色
   */
  const handleAdd = () => {
    roleStore.openFormModal()
  }

  /**
   * 编辑角色
   * @param id 角色ID
   */
  const handleEdit = (id: string) => {
    roleStore.openFormModal(id)
  }

  /**
   * 表单提交
   */
  const handleSubmit = async () => {
    try {
      if (!formRef.value) {
        throw new Error('表单引用不存在')
        return
      }
      
      await formRef.value.validate()
      await roleStore.submitForm()
    } catch (error) {
      throw error
    }
  }
  
  // ------------ 删除操作方法 ------------
  /**
   * 删除角色
   * @param id 角色ID
   */
  const handleDelete = async (id: string) => {
    try {
      Modal.confirm({
        title: t('role.deleteConfirmTitle'),
        content: t('role.deleteConfirmContent', { name: roleList.value.find((item) => item.id === id)?.roleName }),
        okText: t('common.yes'),
        okType: 'danger',
        cancelText: t('common.no'),
        async onOk() {
          loading.value = true;
          await roleStore.removeRoles([id]);
          message.success(t('role.deleteSuccess'));
          if (pagination.value.current && roleList.value.length === 1 && pagination.value.current > 1) {
            pagination.value.current -= 1;
          }
          await roleStore.fetchRoleList(queryParams.value);
        },
      });
    } catch (error) {
      // 错误处理
    } finally {
      loading.value = false;
    }
  };

  /**
   * 批量删除
   */
  const handleBatchDelete = async () => {
    try {
      if (!selectedRowKeys.value.length) {
        message.warning(t('role.selectItemFirst'));
        return;
      }
      Modal.confirm({
        title: t('common.confirm'),
        content: t('role.confirmBatchDelete'),
        okText: t('common.yes'),
        okType: 'danger',
        cancelText: t('common.no'),
        async onOk() {
          loading.value = true;
          await roleStore.removeRoles(selectedRowKeys.value as string[]);
          message.success(t('role.batchDeleteSuccess'));
          selectedRowKeys.value = [];
          await roleStore.fetchRoleList(queryParams.value);
        },
      });
    } catch (error) {
      // 错误处理
    } finally {
      loading.value = false;
    }
  };
  
  // ------------ 状态管理方法 ------------
  /**
   * 修改角色状态
   * @param id 角色ID
   * @param status 状态值
   */
  const handleStatusChange = (id: string, status: number) => {
    roleStore.changeStatus(id, status)
  }
  
  // ------------ 权限相关方法 ------------
  /**
   * 分配权限
   * @param id 角色ID
   */
  const handleAssignPermissions = async (id: string) => {
    try {
      // 先获取角色权限数据
      const success = await roleStore.fetchRolePermissions(id)
      
      if (success) {
        // 确保在DOM更新后再转换权限树
        nextTick(() => {
          if (storePermissionTree.value && storePermissionTree.value.length > 0) {
            // 转换权限树格式
            treeData.value = convertPermissionTreeToAntd(storePermissionTree.value)
            // 获取默认展开的节点
            defaultExpandedKeys.value = getDefaultExpandedKeys(treeData.value)
          } else {
            message.error(t('role.permissionDataEmpty'))
          }
        })
      }
    } catch (error) {
      message.error(t('role.fetchPermissionsFailed'))
    }
  }

  /**
   * 提交权限分配
   */
  const handleSubmitPermissions = () => {
    if (currentRoleId.value) {
      roleStore.savePermissions(currentRoleId.value)
    }
  }
  
  /**
   * 处理权限树选中变化
   * @param keys 选中的键列表
   */
  const handlePermissionCheck = (keys: Key[]) => {
    roleStore.handlePermissionCheck(keys as string[])
  }
  
  // ------------ 辅助方法 ------------
  /**
   * 转换权限树为Ant Design树形控件所需格式
   * @param tree 权限树数据
   * @returns 转换后的树形数据
   */
  const convertPermissionTreeToAntd = (tree: RolePermissionTreeNode[]): DataNode[] => {
    if (!tree || tree.length === 0) {
      return []
    }
    
    return tree.map(item => {
      const node: DataNode = {
        title: item.name,
        key: item.id,
        children: item.children && item.children.length > 0 
          ? convertPermissionTreeToAntd(item.children) 
          : undefined
      }
      return node
    })
  }
  
  /**
   * 获取默认展开的树节点
   * @param tree 树形数据
   * @returns 默认展开的节点键列表
   */
  const getDefaultExpandedKeys = (tree: DataNode[]): string[] => {
    if (!tree || tree.length === 0) {
      return []
    }
    
    const keys: string[] = []
    
    const traverse = (nodes: DataNode[]) => {
      nodes.forEach(node => {
        if (node.key) {
          keys.push(node.key.toString())
        }
        if (node.children && node.children.length > 0) {
          traverse(node.children)
        }
      })
    }
    
    traverse(tree)
    return keys
  }
  
  // ------------ 初始化 ------------
  onMounted(() => {
    fetchRoleList()
  })
  
  /**
   * 获取角色列表
   */
  const fetchRoleList = async () => {
    try {
      // 重置错误状态
      loadError.value = false
      errorMessage.value = ''
      
      await roleStore.fetchRoleList(queryParams.value)
      
      // 检查数据是否为空
      if (roleList.value.length === 0) {
        errorMessage.value = t('role.emptyData')
      }
      
      return roleList.value
    } catch (error: any) {
      loadError.value = true
      errorMessage.value = error?.message || t('role.loadFailed')
      return Promise.reject(error)
    }
  }
  
  return {
    // 状态
    loading,
    submitLoading,
    permissionLoading,
    modalVisible,
    permissionModalVisible,
    roleList,
    selectedRowKeys,
    pagination,
    queryParams,
    form,
    treeData,
    checkedKeys,
    defaultExpandedKeys,
    formRef,
    hasSelected,
    loadError,
    errorMessage,
    
    // 表格交互方法
    onSelectChange,
    handleTableChange,
    
    // 搜索区域方法
    handleSearch,
    handleReset,
    
    // 表单操作方法
    handleAdd,
    handleEdit,
    handleSubmit,
    
    // 删除操作方法
    handleDelete,
    handleBatchDelete,
    
    // 状态管理方法
    handleStatusChange,
    
    // 权限相关方法
    handleAssignPermissions,
    handleSubmitPermissions,
    handlePermissionCheck,
    
    // 数据获取方法
    fetchRoleList
  }
} 